<template>
    <el-dialog title="角色授权" v-model="visable" width="45%" >
        <div class="bs-dialog">
            <el-form ref="addRef" :model="dialogFormData" :rules="dialogFormRules" label-width="auto"
            style="width: 99%;padding-left: 10%;">
                <el-form-item label="当前角色:" >
                    <span style="font-size: 14px;line-height: 0px;color: yellowgreen;font-weight: bolder;">{{ dialogFormData.roleName }}</span>
                </el-form-item>
                <el-form-item label="菜单权限:" prop="rightsIdList">
                    <div style="text-align: left;">
                        <el-checkbox v-model="expandAll" @change="expandEvent">展开全部/折叠全部</el-checkbox>
                        <el-checkbox v-model="selectAll" @change="selectEvent" >全选/全不选</el-checkbox>
                    </div>
                </el-form-item>
                <div class="rightsTree">
                    <el-tree ref="treeRef" 
                        v-model="dialogFormData.parentRightsId" 
                        show-checkbox 
                        :data="treeData"
                        node-key="rightsId" 
                        style="width: 100%" 
                        :render-after-expand="false" 
                        :props="defaultProps"
                        :check-on-click-node="false" 
                        :default-expanded-keys="expandedAllKeys" 
                        @check="menuCheckboxCheck" 
                        @check-change="menuCheckBoxChange"
                        @node-click="menuClick"
                        />
                </div>
                <div style="position: absolute;width: 40%;float: right;top: 24%;right: 2%;text-align: left">
                    <template v-for="item in currentMenuBtnRightsList" :key="item.rightsId">
                        <el-checkbox 
                        style="display: inline-block;padding: 5px;"  
                        :disabled="currentMenuBtnRightsDisable"
                        @change="(val)=>btnChange(val, item)"
                        :model-value="checkedBtnRights(item.rightsId)"
                        >{{ item.rightsName }} </el-checkbox>
                    </template>
                </div>
            </el-form>
        </div>
        <div class="bs-dialog-footer" style="position: absolute;bottom: 20px;right: 20px;">
            <el-button size="small" @click="visable = false"> 取消 </el-button>
            <el-button size="small" type="primary" @click="save"> 保存 </el-button>
        </div>
    </el-dialog>
</template>
<script>
import { lisRights } from '@/api/system/menu'
import { updateRole, getRoleById, listAllRole } from '@/api/system/role'
export default {
    data() {
        return {
            treeData: [], // 菜单列表
            treeDataBak: [], // 备份数据
            expandAll: false, // 展开所有
            selectAll: false, // 全选
            expandedAllKeys: [],
            treeIds: [], // 所有树节点ID
            defaultProps: {
                children: 'children',
                label: 'rightsName',
                value: 'rightsId'
            },
            visable: false,
            dialogFormData: {
                roleId: '',
                roleName: '',
                rightsIdList: [],
            },
            dialogFormRules:{},
            btnRightsList: [], // 所有的按钮权限列表
            currentMenuBtnRightsList: [], // 当前菜单的可选的, 按钮权限列表
            currentMenuHasSelectedBtnRightsList:[], // 当前菜单已选中的按钮权限列表
            currentMenuBtnRightsDisable:true , // 当前菜单的按钮权限列表是否可选
            rightsList:[], // 所有权限列表(带parentID)
        }
    },
    methods: {
        // 菜单权限回显是否选中
        checkedBtnRights(rightsId){
            return  this.currentMenuHasSelectedBtnRightsList.includes(rightsId)
        },
        openModal(roleId) {
            this.visable = true
            this.selectAll = false
            this.expandAll = false
            this.$nextTick(() => {
                // 获取菜单列表
                lisRights({}).then(res => {
                    if (res.code === 1) {
                        this.btnRightsList = res.extraData
                        this.treeData = res.data
                        this.treeDataBak = [...res.data]
                        this.getAllNodeId(res.data)
                    }
                })
                // 获取修改的角色信息
                getRoleById({ 'roleId': roleId }).then(res => {
                    this.$refs.treeRef.setCheckedKeys([])
                    if (res.code === 1) {
                        this.$refs.treeRef.setCheckedKeys([...res.data.rightsIdList])
                        this.currentMenuHasSelectedBtnRightsList = [...res.extraData]
                        this.expandedAllKeys = [...res.data.rightsIdList]
                        this.rightsList = [...res.data.rightsList]
                        this.dialogFormData.roleId = res.data.roleId
                        this.dialogFormData.roleName = res.data.roleName
                        this.dialogFormData.rightsIdList = [...res.data.rightsIdList]
                        this.dialogFormData.roleStatus = res.data.roleStatus
                        this.dialogFormData.parentRoleId = res.data.parentRoleId
                    }
                })
            })
        },
        // 获取所有树节点id
        getAllNodeId(treeNodes) {
            treeNodes.forEach(item => {
                this.treeIds.push(item.rightsId)
                if (item.children && item.children.length > 0) {
                    this.getAllNodeId(item.children)
                }
            })
        },
        /**
         * 菜单复选框点击事件
         * @param {*} currentNode   点击的当前节点
         * @param {*} selectedNodes 选中的节点对象
         */
        menuCheckboxCheck(currentNode, selectedNodes) {
            this.dialogFormData.rightsIdList = selectedNodes.checkedKeys
        },
        /**
         * 菜单复选框变更事件
         * @param node      当前节点
         * @param checked   是否选中
         * @param hasChecked    节点的字树是否有被选中的节点
         */
         menuCheckBoxChange(node,checked,hasChecked){
            // 取消选中
            if (checked == false) {
                this.dialogFormData.rightsIdList = this.dialogFormData.rightsIdList.filter(item=>item != node.rightsId)
                // 父菜单取消选中, btn权限列表要全部取消选中
                let btnIdList = this.rightsList.filter(item=>item.parentRightsId == node.rightsId).map(item=>item.rightsId)
                this.currentMenuHasSelectedBtnRightsList = this.currentMenuHasSelectedBtnRightsList.filter(id => !btnIdList.includes(id))
            } else {
                this.dialogFormData.rightsIdList.push(node.rightsId)
            }
            let rightsId = node.rightsId
            this.currentMenuBtnRightsList = this.btnRightsList.filter(item=>item.parentRightsId == rightsId)
            // 当前菜单的按钮权限列表是否可选
            this.currentMenuBtnRightsDisable = this.dialogFormData.rightsIdList.findIndex(item=>item == node.rightsId) == -1 ? true : false

        },
        // btn权限变更事件
        btnChange(checked,item){
            // 选中按钮权限,则加入到菜单权限列表中，否则移除掉
            if (checked == true) {
                this.currentMenuHasSelectedBtnRightsList.push(item.rightsId)
            } else {
                this.dialogFormData.rightsIdList = this.dialogFormData.rightsIdList.filter(item1=>item1 != item.rightsId)
                this.currentMenuHasSelectedBtnRightsList = this.currentMenuHasSelectedBtnRightsList.filter(item1=>item1 != item.rightsId)
            }
        },
        // 菜单节点事件
        menuClick(node){
            this.currentMenuBtnRightsList = this.btnRightsList.filter(item=>item.parentRightsId == node.rightsId)
            this.currentMenuBtnRightsDisable = this.dialogFormData.rightsIdList.findIndex(item=>item == node.rightsId) == -1 ? true : false
        },
        // 点击展开/收起
        expandEvent(val) {
            this.expandAll = val
            if (val === true) {
                this.expandedAllKeys = [...this.treeIds]
            } else {
                // 收起, 先把tree数据置空, 再赋值
                this.treeData = []
                this.expandedAllKeys = []
                // 必须放在
                this.$nextTick(() => {
                    this.treeData = [...this.treeDataBak]
                })
            }
        },
        // 菜单权限的全选/非全选
        selectEvent(val) {
            this.selectAll = val
            if (val === true) {
                this.$refs.treeRef.setCheckedKeys([...this.treeIds])
                this.dialogFormData.rightsIdList = [...this.treeIds]
            } else {
                this.selectAllKeys = []
                this.$refs.treeRef.setCheckedKeys([])
                this.dialogFormData.rightsIdList = []
            }
        },
        // 保存
    save() {
      this.$refs['addRef'].validate((valid) => {
        if (valid) {
            // 保存时, 带上按钮权限
          this.dialogFormData.rightsIdList.push(...this.currentMenuHasSelectedBtnRightsList)
          updateRole(this.dialogFormData).then(res => {
            if (res.code == 1) {
              this.$message.success('操作成功')
              this.visable = false
              // 刷新父组件中的表格数据
              this.$emit('flushTable', {})
            } else {
              this.$message.error(res.msg)
            }
          }).catch((error) => {
          })
        }
      })
    },
    }
}
</script>
<style scoped>
    .rightsTree {
        border-radius: 3px;
        padding:10px;
        height: 60vh;
        max-height: 60vh;
        width: 40%;
        overflow-y: scroll;
    }
    .rightsTree::-webkit-scrollbar {
        display: none;
    }
    >>>.el-checkbox__label{
        font-size: 14px !important;
    }
    >>> .el-form-item__label{
        font-size: 13px !important;
    }
</style>